#pragma once

#include <functional>
#include <string>
#include <signal.h>
#include "Log.hpp"
#include "Socket.hpp"

using namespace std;

using func_t = function<string(string &data)>;

class TcpServer
{
public:
    TcpServer(uint16_t port, func_t callback)
        : _port(port), _callback(callback)
    {
    }

    bool InitServer()
    {
        _listensock.Socket();
        _listensock.Bind(_port);
        _listensock.Listen();
        lg(Info, "init server .... done");
        return true;
    }

    void Start()
    {
        signal(SIGCHLD, SIG_IGN); // 调用系统调用daemon时，仍然需要手动忽略信号
        signal(SIGPIPE, SIG_IGN);
        signal(SIGINT, SIG_IGN);

        while (1)
        {
            std::string clientip;
            uint16_t clientport;

            int accsock = _listensock.Accept(&clientip, &clientport);
            if (accsock < 0)
                continue;
            lg(Info, "accept a new link, sockfd: %d, clientip: %s, clientport: %d", accsock, clientip.c_str(), clientport);

            // 提供服务
            std::string inbuffer_stream; // 接收到的流数据
            while (1)
            {
                char buffer[1280];
                ssize_t n = recv(accsock, buffer, sizeof(buffer), 0);

                if (n > 0)
                {
                    buffer[n] = '\0';
                    inbuffer_stream += buffer;

                    lg(Debug, "debug:\n%s", inbuffer_stream.c_str());

                    while (true)
                    {
                        std::string info = _callback(inbuffer_stream);  //可能接收到了多个数据包，需要分割处理
                        if (info.empty())
                            break;
                        lg(Debug, "debug, response:\n%s", info.c_str());
                        lg(Debug, "debug:\n%s", inbuffer_stream.c_str());
                        write(accsock, info.c_str(), info.size());
                    }
                }
                else if (n == 0)    
                    break;
                else
                    break;
            }

            close(accsock);
        }
    }

private:
    uint16_t _port;
    Sock _listensock;
    func_t _callback;
};